package com.ctl.szmd.szmd.data.repository

import androidx.paging.PagingConfig
import com.blankj.utilcode.util.LogUtils
import com.ctl.lib_common.utils.livebus.LiveBus
import com.ctl.szmd.szmd.data.remote.AppService
import com.ctl.szmd.szmd.ui.Constants
import com.ctl.szmd.szmd.utils.DownloadUtils
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * created by : chentl
 * Date: 2020/07/31
 */
class RepositoryImpl(
    val api: AppService,
    private val pageConfig: PagingConfig
) : Repository {

    override fun downloadFile(url: String, name: String) {
        val call = api.downloadFile(url)
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
                LogUtils.i("下载失败")
            }

            override fun onResponse(call: Call<ResponseBody?>, response: Response<ResponseBody?>) {
                if (response.isSuccessful) {
                    LogUtils.i(response)
                    val file = DownloadUtils().writeResponseBodyToDisk(response.body(), name)
                    if (file != null) {
                        LogUtils.i("下载成功${file.absolutePath}")
                        LiveBus.get(Constants.LIVE_BUS_FILE_DOWNLOAD_FINISH_OPEN).post(file)
                    } else {
                        LogUtils.i("文件不存在")
                    }
                } else {
                    LogUtils.i("服务器返回错误")
                }
            }
        })
    }

}